<template>
  <k-section type="simple" :title="title">
    <k-section collapse type="border" @expanded="onExpandedToEdit">
      <template #head>
        <div class="head-row-wrapper">
          <el-icon size="32"><Stopwatch /></el-icon>
          <div class="head-row-col">
            <span v-if="probeType === ''">编辑</span>
            <span v-else>{{ probeType }}</span>

            <div class="text-xs text-gray-400">
              {{
                `${probe?.initialDelaySeconds ?? 0}s初始延迟,${probe?.timeoutSeconds ?? 0}s超时时间`
              }}
            </div>
          </div>

          <div v-if="probe?.exec" class="head-row-col">
            <span>{{ probe.exec.command.join(",") }}</span>
            <div>命令</div>
          </div>

          <div v-if="probe?.httpGet" class="head-row-col">
            <span>{{ probe.httpGet.scheme }}</span>
            <div>类型</div>
          </div>

          <div v-if="probe?.httpGet" class="head-row-col">
            <span>{{ probe.httpGet.path }}</span>
            <div>路径</div>
          </div>

          <div v-if="probe?.httpGet" class="head-row-col">
            <span>{{ probe.httpGet.port ?? "-" }}</span>
            <div>端口</div>
          </div>

          <div v-if="probe?.tcpSocket" class="head-row-col">
            <span>{{ probe.tcpSocket.port ?? "-" }}</span>
            <div>端口</div>
          </div>

          <el-button circle icon="Delete" @click.stop="probeType = ''" />
        </div>
      </template>

      <div class="edit-body">
        <el-segmented v-model="probeType" :options="probeTypeList" block />
        <el-form v-if="probe" v-model="probe" label-position="top">
          <KFormItem
            v-if="isCommandType"
            v-model="inputCommand"
            label="命令"
            class="w-full"
            prop="exec.command"
            :disabled="readonly"
            :rows="3"
            :rules="[RequiredRule]"
            required
            item-type="textarea"
            @on-change="onInputCommandChanged"
          >
            <div class="sub-description">使用半角逗号（,）分隔多条命令。</div>
          </KFormItem>

          <el-form-item v-if="isHttpGetType" label="路径">
            <div class="flex gap-2 w-full px-4 py-1 bg-slate-300 rounded-md">
              <KoDataItem
                v-model="probe.httpGet.scheme"
                class="flex-grow"
                item-type="flatSelect"
                :selections="['HTTP', 'HTTPS']"
              />
              <KoDataItem
                v-model="probe.httpGet.path"
                item-type="input"
                class="flex-grow"
                placeholder="请求路径"
                default="/"
              />
              <KoDataItem
                v-model="probe.httpGet.port"
                class="flex-grow"
                item-type="clearNumber"
                placeholder="请求端口"
                default="80"
              />
            </div>
          </el-form-item>

          <el-row v-if="isTcpSocketType">
            <el-col :span="12">
              <el-form-item label="端口" :rules="[RequiredRule]">
                <KoDataItem
                  v-model="probe.tcpSocket.port"
                  class="w-full"
                  item-type="clearNumber"
                  placeholder="请求端口"
                  default="80"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <KFormItem
                v-model="probe.initialDelaySeconds"
                label="初始延迟(s)"
                prop="initialDelaySeconds"
                :disabled="readonly"
                item-type="clearNumber"
                default="0"
              >
                <div class="sub-description">
                  容器启动后探针启动前的延迟时间。
                </div>
              </KFormItem>
            </el-col>
            <el-col :span="12">
              <KFormItem
                v-model="probe.timeoutSeconds"
                label="超时时间(s)"
                prop="timeoutSeconds"
                :disabled="readonly"
                item-type="input"
                default="0"
              >
                <div class="sub-description">
                  探针超时时间。探针超时后，检查将被视为失败。取值必须为整数，最小值为
                  0。
                </div>
              </KFormItem>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <KFormItem
                v-model="probe.periodSeconds"
                prop="periodSeconds"
                label="检查间隔(s)"
                :disabled="readonly"
                item-type="clearNumber"
                default="10"
              >
                <div class="sub-description">
                  执行检查的时间间隔。取值必须为整数，最小值为 1。
                </div>
              </KFormItem>
            </el-col>
            <el-col :span="12">
              <KFormItem
                v-model="probe.successThreshold"
                prop="successThreshold"
                label="成功阈值(s)"
                :disabled="readonly"
                item-type="clearNumber"
                default="1"
              >
                <div class="sub-description">
                  检查失败后再次被视为成功所需的最小连续成功次数。最小值为
                  1。对于存活探针和启动探针，此参数值必须为 1。
                </div>
              </KFormItem>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <KFormItem
                v-model="probe.failureThreshold"
                prop="failureThreshold"
                label="失败阈值(s)"
                :disabled="readonly"
                item-type="clearNumber"
                default="3"
              >
                <div class="sub-description">
                  检查成功后再次被视为失败所需的最小连续失败次数。最小值为 1。
                </div>
              </KFormItem>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </k-section>
  </k-section>
</template>

<script setup lang="ts">
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import KFormItem from "@/views/domain/kubeHud/views/components/k-form-item/index.vue";
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import { Container, Probe } from "../../../api/k8s";
import { computed, onMounted, reactive, ref } from "vue";
import { HealthCheckProbeType } from "./types";
import { useI18n } from "vue-i18n";
import KSection from "@/views/domain/kubeHud/views/components/k-section/index.vue";
import { useFormRule } from "../../../utils/rules";
const { t } = useI18n();
const { RequiredRule } = useFormRule();

type Prop = {
  healthCheckType?: HealthCheckProbeType;
  healthCheckHelper?: string;
  readonly?: boolean;
};

const props = withDefaults(defineProps<Prop>(), {
  readonly: false
});

const probe = defineModel<Probe>("probe");
const emits = defineEmits(["delete"]);

const title = computed(() => {
  switch (props.healthCheckType) {
    case "liveness":
      return t("business.workload.readiness_check");
    case "readiness":
      return t("business.workload.liveness_check");
    case "startup":
      return t("business.workload.startup_check");
    default:
      return "";
  }
});

const inputCommand = ref<string>(probe.value.exec?.command.join(",") ?? "");
const onInputCommandChanged = (cmd: string) => {
  console.log("on InputCommandChanged", cmd);
  if (isCommandType.value) {
    probe.value.exec.command = cmd.split(",");
  }
};

const probeTypeList = ["命令", "HTTP请求", "TCP检查"];

const isCommandType = computed(() => !!(probe.value?.exec ?? false));
const isHttpGetType = computed(() => !!(probe.value?.httpGet ?? false));
const isTcpSocketType = computed(() => !!(probe.value?.tcpSocket ?? false));

const onExpandedToEdit = (e: boolean) => {
  if (
    e &&
    !isCommandType.value &&
    !isHttpGetType.value &&
    !isTcpSocketType.value
  ) {
    // probeType.value = probeTypeList[0] as any;
  }
};

const initWith = (merge: Probe): Probe => {
  const initProbe: Probe = {
    initialDelaySeconds: 0,
    timeoutSeconds: 1,
    periodSeconds: 10,
    successThreshold: 1,
    failureThreshold: 3
  };
  return Object.assign(initProbe, merge);
};

const probeType = computed({
  get() {
    if (probe.value?.exec) {
      return "命令";
    } else if (probe.value?.httpGet) {
      return "HTTP请求";
    } else if (probe.value?.tcpSocket) {
      return "TCP检查";
    } else {
      return "";
    }
  },
  set(tp) {
    switch (tp) {
      case "命令":
        inputCommand.value = "";
        probe.value = initWith({
          exec: {
            command: []
          }
        });
        break;
      case "HTTP请求":
        probe.value = initWith({
          httpGet: {
            path: "",
            port: 80,
            scheme: "HTTP",
            httpHeaders: []
          }
        } as any);
        break;
      case "TCP检查":
        probe.value = initWith({
          tcpSocket: {
            port: 80
          }
        });
        break;
      case "":
        emits("delete");
        break;
      default:
        break;
    }
  }
});
</script>

<style lang="scss" scoped>
.head-row-wrapper {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;

  .head-row-col {
    display: flex;
    flex-direction: column;
    flex-grow: 1;

    > span {
      min-height: 20px;
    }
    > div {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}

.edit-body {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .el-segmented {
    --el-segmented-item-selected-color: var(--el-fill-color-light);
    --el-segmented-item-selected-bg-color: var(--el-color-primary);
    --el-border-radius-base: 16px;
    border: var(--el-border);
  }
}

.sub-description {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 20px;
}
</style>
